<template>
  <view class="add-project-container">
    <view class="back-btn" @click="goBack">
      返回
    </view>
    <view class="header-wrapper">
      <view class="header">添加项目</view>
      <view class="add-form-btn" @click="addForm">+</view>
    </view>

    <view v-for="(formData, index) in formList" :key="index">
      <view class="form-wrapper">
        <view class="form-item">
          <label>项目名称</label>
          <input type="text" v-model="formData.name" placeholder="请输入项目名称" :disabled="false" />
        </view>

        <view class="form-item">
          <label>项目成员</label>
          <input type="text" v-model="formData.projectMember" placeholder="请输入项目成员，用逗号分隔" :disabled="false" />
        </view>

        <view class="form-item">
          <label>投票类型</label>
          <input type="text" v-model="formData.type" placeholder="投票类型" :disabled="false" />
        </view>
        <view class="form-item">
          <label>照片</label>
          <view class="photo-container">
            <view class="photo-upload" @click="uploadPhoto(index)">
              <text>+</text>
            </view>
            <view v-for="(photo, photoIndex) in formData.photos" :key="photoIndex" class="photo-item">
              <image :src="photo.url" mode="aspectFill" @click="previewPhoto(index, photoIndex)" />
              <view class="delete-btn" @click.stop="deletePhoto(index, photoIndex)">×</view>
            </view>
          </view>
          <text class="photo-tip">最多上传6张照片</text>
        </view>

        <view class="form-item">
          <label>介绍</label>
          <textarea v-model="formData.description" placeholder="请输入项目介绍（1500字以内）" />
          <text class="word-count">{{ formData.description.length }}/1500</text>
        </view>

        <view class="button-wrapper">
          <button class="cancel-btn" @click="cancelAdd(index)">撤销添加</button>
          <button class="submit-btn" @click="submitProject(index)">完成添加</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { insertProject } from '@/api/vote.js';
import { onLoad } from '@dcloudio/uni-app';

// 定义一个 ref 来存储 voteId
const voteIdRef = ref('');

onLoad((options) => {
    const voteId = options.voteId;
    console.log('接收到的 voteId:', voteId);
    voteIdRef.value = voteId;

    // 初始化表单数据时使用 voteId
    formList.value = [
        {
            voteId: voteIdRef.value,
            name: '',
            projectMember: '',
            photos: [],
            description: '',
            type: "",
            totalVotes:0,
            totalInsideVotes:0
        }
    ];
});

const formList = ref([]);

// 添加新表单
const addForm = () => {
    formList.value.push({
        voteId: voteIdRef.value,
        name: '',
        projectMember: '',
        photos: [],
        description: '',
        type: "",
        totalVotes:0,
        totalInsideVotes:0
    });
};

// 上传照片方法
const uploadPhoto = (index) => {
    // 实际项目中需要实现照片上传逻辑
    console.log('上传照片');
    // 示例：添加一张示例照片
    if (formList.value[index].photos.length < 6) {
        formList.value[index].photos.push({
            url: 'https://picsum.photos/200/200?random=' + Date.now(),
            id: Date.now()
        });
    }
};

// 预览照片
const previewPhoto = (formIndex, photoIndex) => {
    console.log('预览照片:', formIndex, photoIndex);
    // 实际项目中需要实现照片预览逻辑
};

// 删除照片
const deletePhoto = (formIndex, photoIndex) => {
    formList.value[formIndex].photos.splice(photoIndex, 1);
};

const goBack = () => {
    uni.switchTab({ url: '/pages/myVote/myVote' });
};

// 提交项目
const submitProject = async (index) => {
    if (formList.value.length > 1) {
        uni.showModal({
            title: '提示',
            content: '检测到有多个添加模块，是否全部添加？',
            success: async (res) => {
                if (res.confirm) {
                    for (let i = 0; i < formList.value.length; i++) {
                        const formData = formList.value[i];
                        if (!formData.name || !formData.projectMember) {
                            alert('项目名称和项目成员不能为空');
                            return;
                        }
                        await insertProject(formData);
                    }
                    uni.switchTab({ url: '/pages/myVote/myVote' });
                }
            }
        });
    } else {
        const formData = formList.value[index];
        if (!formData.name || !formData.projectMember) {
            alert('项目名称和项目成员不能为空');
            return;
        }
        const res = await insertProject(formData);
        uni.switchTab({ url: '/pages/myVote/myVote' });
    }
};

// 撤销添加
const cancelAdd = (index) => {
    if (formList.value.length > 1) {
        formList.value.splice(index, 1);
    }
};
</script>

<style scoped>
/* 样式部分保持不变 */
.add-project-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header {
  font-size: 20px;
  font-weight: bold;
  margin: auto;
  padding: 15px 0;
  color: #333;
}

.add-form-btn {
  font-size: 24px;
  color: #007AFF;
  cursor: pointer;
  margin-right: 20px;
}

.back-btn {
  position: absolute;
  left: 23px;
  top: 55px;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 16px;
  font-weight: normal;
  color: black;
  font-weight: bold;
}

.form-wrapper {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input {
  width: 95%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
  z-index: 100;
}

textarea {
  height: 120px;
  resize: none;
}

.word-count {
  display: block;
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.photo-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.photo-upload {
  width: 80px;
  height: 80px;
  border: 1px dashed #ddd;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #999;
  cursor: pointer;
}

.photo-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
}

.photo-item image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  text-align: center;
  line-height: 20px;
  cursor: pointer;
}

.photo-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  display: block;
}

.button-wrapper {
  display: flex;
  gap: 10px;
}

.cancel-btn {
  width: 50%;
  padding: 12px;
  background-color: #FF0000;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.cancel-btn:active {
  background-color: #CC0000;
}

.submit-btn {
  width: 50%;
  padding: 12px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.submit-btn:active {
  background-color: #0062CC;
}
</style>